package com.zprmb.udzt;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Application;
import android.app.Notification;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.multidex.MultiDex;
import android.support.v4.app.NotificationCompat;
import android.support.v4.hardware.fingerprint.FingerprintManagerCompat;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.RemoteViews;
import android.widget.Toast;

import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.squareup.picasso.Picasso;
import com.squareup.picasso.Target;
import com.tencent.bugly.crashreport.CrashReport;
import com.tencent.smtt.sdk.QbSdk;
import com.tencent.smtt.sdk.TbsDownloader;
import com.tencent.smtt.sdk.TbsListener;
import com.umeng.analytics.AnalyticsConfig;
import com.umeng.analytics.MobclickAgent;
import com.umeng.message.IUmengRegisterCallback;
import com.umeng.message.PushAgent;
import com.umeng.message.UTrack;
import com.umeng.message.UmengMessageHandler;
import com.umeng.message.entity.UMessage;
import com.umeng.socialize.PlatformConfig;
import com.umeng.socialize.UMShareAPI;
import com.zprmb.udzt.ScreenListener.ScreenStateListener;
import com.zprmb.udzt.service.MyPushIntentService;
import com.zprmb.udzt.util.FileUtils;
import com.zprmb.udzt.util.ToastUtil;
import com.zprmb.udzt.vo.RequestQueue;
import com.zprmb.udzt.vo.toolbox.Volley;

import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author shenshao
 */
public class BbtApplication extends Application {

    public ImageLoader imageLoader;
    private DisplayImageOptions options;
    private static BbtApplication application = null;
    private List<Activity> records = new ArrayList<Activity>();
    private RequestQueue mQueue;
    private static Context context;
    private SharedPreferences sha;
    private static final String TAG = BbtApplication.class.getName();
    PushAgent mPushAgent;
    private String channel;

    @TargetApi(Build.VERSION_CODES.ICE_CREAM_SANDWICH)
    public void onCreate() {
        MultiDex.install(this);
        super.onCreate();

        initImageLoader(getApplicationContext());

        sha = getSharedPreferences("config", MODE_PRIVATE);
//        Config.DEBUG = true;
        context = getApplicationContext();
        FingerprintManagerCompat managerCompat = FingerprintManagerCompat.from(context);
        CrashReport.initCrashReport(getApplicationContext(), "a36a8f6303", false);

//        CrashReport.initCrashReport(getApplicationContext(), "0910e45f-b0f8-4d87-94c4-45d6feb90b20", false);
//        MultiDex.install(this);
        Editor ed = sha.edit();
        ed.putString("time", "0");
        ed.putInt("isopen", 1);
        try {
            if (!managerCompat.isHardwareDetected()) { //判断设备是否支持
                ed.putInt("finger", 0);
//            ToastUtil.showCenterToast(context,"0");
            } else {
                ed.putInt("finger", 1);
//            ToastUtil.showCenterToast(context,"1");
            }
        } catch (Exception e) {
            ed.putInt("finger", 0);
        }


        ed.commit();
        UMShareAPI.get(this);
//		 Log.e("version", SocializeConstants.SDK_VERSION);
        TbsDownloader.needDownload(getApplicationContext(), false);
        QbSdk.preInit(getApplicationContext());
        QbSdk.getTbsVersion(getContext());
        QbSdk.initX5Environment(getContext(), null);
        QbSdk.PreInitCallback cb = new QbSdk.PreInitCallback() {

            @Override
            public void onViewInitFinished(boolean arg0) {
                // TODO Auto-generated method stub
                Log.e("app", " onViewInitFinished is " + arg0);

            }

            @Override
            public void onCoreInitFinished() {
                // TODO Auto-generated method stub

            }
        };

        QbSdk.setTbsListener(new TbsListener() {
            @Override
            public void onDownloadFinish(int i) {
                Log.d("app", "onDownloadFinish");
            }

            @Override
            public void onInstallFinish(int i) {
                Log.d("app", "onInstallFinish");
            }

            @Override
            public void onDownloadProgress(int i) {
                Log.d("app", "onDownloadProgress:" + i);
            }
        });


        mPushAgent = PushAgent.getInstance(this);
        mPushAgent.setDebugMode(true);


        ScreenListener l = new ScreenListener(this);
        l.begin(new ScreenStateListener() {

            @Override
            public void onUserPresent() {
                Log.e("onUserPresent", "onUserPresent");
            }

            @Override
            public void onScreenOn() {
                Log.e("onScreenOn", "onScreenOn");
            }

            @Override
            public void onScreenOff() {
                Log.e("onScreenOff", "onScreenOff");
                Editor ed = sha.edit();
                ed.putString("time", ondata());
                ed.putInt("isopen", 1);
                ed.putString("isTop", "1");
                ed.commit();
            }
        });
        imageLoader = ImageLoader.getInstance();
        application = this;
        MobclickAgent.updateOnlineConfig(this);
        MobclickAgent.setDebugMode(true);
        AnalyticsConfig.enableEncrypt(true);
//		mQueue = Volley.newRequestQueue(getApplicationContext());
        UmengDate("1");
        //TCAgent.LOG_ON=true;
        //TCAgent.init(this);
        //TCAgent.setReportUncaughtExceptions(true);
        BbtApplication.getInstance().download("https://rmbboximage.b0.upaiyun.com/appads0");
        UmengMessageHandler messageHandler = new UmengMessageHandler() {
            /**
             * 参考集成文档的1.6.3
             * http://dev.umeng.com/push/android/integration#1_6_3
             * */
            @Override
            public void dealWithCustomMessage(final Context context, final UMessage msg) {
                new Handler().post(new Runnable() {

                    @Override
                    public void run() {
                        // TODO Auto-generated method stub
                        // 对自定义消息的处理方式，点击或者忽略
                        boolean isClickOrDismissed = true;
                        if (isClickOrDismissed) {
                            //自定义消息的点击统计
                            UTrack.getInstance(getApplicationContext()).trackMsgClick(msg);
                        } else {
                            //自定义消息的忽略统计
                            UTrack.getInstance(getApplicationContext()).trackMsgDismissed(msg);
                        }
                        Toast.makeText(context, msg.custom, Toast.LENGTH_LONG).show();
                    }
                });
            }
            /**
             * 参考集成文档的1.6.4
             * http://dev.umeng.com/push/android/integration#1_6_4
             * */
            @Override
            public Notification getNotification(Context context,
                                                UMessage msg) {
                Log.d("333333333333333", msg.url);
                switch (msg.builder_id) {
                    case 1:
                        Log.e("builder", msg.builder_id + "");
                        NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
                        RemoteViews myNotificationView = new RemoteViews(context.getPackageName(), R.layout.notification_view);
                        myNotificationView.setTextViewText(R.id.notification_title, msg.title);
                        myNotificationView.setTextViewText(R.id.notification_text, msg.text);
                        myNotificationView.setImageViewBitmap(R.id.notification_large_icon, getLargeIcon(context, msg));
                        myNotificationView.setImageViewResource(R.id.notification_small_icon, getSmallIconId(context, msg));
                        builder.setContent(myNotificationView)
                                .setSmallIcon(R.drawable.ud_logo)
                                .setTicker(msg.ticker)
                                .setAutoCancel(true);

                        return builder.build();

                    default:
//                        Toast.makeText(context, "aaaaaa", Toast.LENGTH_SHORT).show();
                        //默认为0，若填写的builder_id并不存在，也使用默认。
                        Log.e("builder", msg.builder_id + "");
                        return super.getNotification(context, msg);
                }
            }
        };
//        mPushAgent.setMessageHandler(messageHandler);

        /**
         * 该Handler是在BroadcastReceiver中被调用，故
         * 如果需启动Activity，需添加Intent.FLAG_ACTIVITY_NEW_TASK
         * 参考集成文档的1.6.2
         * http://dev.umeng.com/push/android/integration#1_6_2
         * */
     /*   UmengNotificationClickHandler notificationClickHandler = new UmengNotificationClickHandler() {
            @Override
            public void dealWithCustomAction(Context context, UMessage msg) {
//				Toast.makeText(context, msg.custom, Toast.LENGTH_LONG).show();
                LogUtils.e("推送消息", msg.custom + msg.extra.size() + "*");
//                Intent intent = new Intent(getApplicationContext(), MainActivity.class);
//                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                Toast.makeText(context, "cestuisong", Toast.LENGTH_SHORT).show();
                Intent intent = new Intent(getApplicationContext(), MainActivity2.class);
//                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    for (Map.Entry<String, String> entry : msg.extra.entrySet()) {
                    String key = entry.getKey();
                    String value = entry.getValue();
                    if (key.equals("tabbarSelectIndex")) {
                        intent.putExtra(key, Integer.parseInt(value));
                    } else {
                        intent.putExtra(key, value);
                    }
                    Log.e("自定义参数", key + "========" + value);
//			    intent.putExtra("id", "C9FD6AB5-0E3C-11E6-AE96-5254002EAABD");
//			    intent.putExtra("name", "定期D16043001");
//			    intent.putExtra("isred", "true");


                }
                startActivity(intent);
            }
        };*/

//        CustomNotificationHandler customNotificationHandler = new CustomNotificationHandler();
        //使用自定义的NotificationHandler，来结合友盟统计处理消息通知
        //参考http://bbs.umeng.com/thread-11112-1-1.html0
        //CustomNotificationHandler notificationClickHandler = new CustomNotificationHandler();
//        mPushAgent.setNotificationClickHandler(notificationClickHandler);


        mPushAgent.register(new IUmengRegisterCallback() {

            @Override
            public void onSuccess(String deviceToken) {
                //注册成功会返回device token
                Log.e("嘻嘻", deviceToken);
            }

            @Override
            public void onFailure(String s, String s1) {
                Log.e("推送失败", s + "=====" + s1);
            }
        });
//		if (MiPushRegistar.checkDevice(this)) {
//            MiPushRegistar.register(this, "2882303761517400865", "5501740053865");
//		}
        mPushAgent.setPushIntentServiceClass(MyPushIntentService.class);
        registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {

            @Override
            public void onActivityStopped(Activity activity) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onActivityStarted(Activity activity) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onActivitySaveInstanceState(Activity activity, Bundle outState) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onActivityResumed(Activity activity) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onActivityPaused(Activity activity) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onActivityDestroyed(Activity activity) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onActivityCreated(Activity activity, Bundle savedInstanceState) {
                // TODO Auto-generated method stub

            }
        });
    }

    {
        //微信 wx12342956d1cab4f9,a5ae111de7d9ea137e88a5e02c07c94d
//        PlatformConfig.setWeixin("wx967daebe835fbeac", "5bb696d9ccd75a38c8a0bfe0675559b3");
//	    PlatformConfig.setWeixin("wx9a54b4bfda0b887b", "15bee1617f20e93338c7e035f97126c1");
        PlatformConfig.setWeixin("wx4dacde87d692710c", "dea648bc240feb77d3b5b69b69880d15");
        //豆瓣RENREN平台目前只能在服务器端配置
        //新浪微博
//        PlatformConfig.setSinaWeibo("886181634","66b39ab3e2d80885a668260735373099");

        //易信
        PlatformConfig.setYixin("yxc0614e80c9304c11b0391514d09f13bf");
        PlatformConfig.setQQZone("1106083674", "Bso7Ech0zE1cYmZ1");
        PlatformConfig.setTwitter("3aIN7fuF685MuZ7jtXkQxalyi", "MK6FEYG63eWcpDFgRYw4w9puJhzDl0tyuqWjZ3M7XJuuG7mMbO");
        PlatformConfig.setAlipay("2015111700822536");
        PlatformConfig.setLaiwang("laiwangd497e70d4", "d497e70d4c3e4efeab1381476bac4c5e");
        PlatformConfig.setPinterest("1439206");

    }


    public static Context getContext() {
        return context;
    }

    public RequestQueue getRequestQueue() {
        // lazy initialize the request queue, the queue instance will be
        // created when it is accessed for the first time
        if (mQueue == null) {
            mQueue = Volley.newRequestQueue(getApplicationContext());
        }

        return mQueue;
    }

    public static BbtApplication getInstance() {
        return application;
    }

    public String ondata() {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
        Date curDate = new Date(System.currentTimeMillis());//获取当前时间
        String str = formatter.format(curDate);
        return str;
    }

    private void UmengDate(String what) {
        Log.d("22222222", what);


        try {
            ApplicationInfo appInfo = this.getPackageManager()
                    .getApplicationInfo(getPackageName(),
                            PackageManager.GET_META_DATA);
            String msg = appInfo.metaData.getString("UMENG_CHANNEL");
            Map<String, String> m = new HashMap<String, String>();
            m.put(msg, msg);
            MobclickAgent.onEventValue(this, what, m,
                    1);

        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
    }

    public String getMetaData(Context context) {

        PackageManager packageManager = context.getPackageManager();
        ApplicationInfo applicationInfo;
        try {
            applicationInfo = packageManager.getApplicationInfo(context.getPackageName(), PackageManager.GET_META_DATA);
            if (applicationInfo != null && applicationInfo.metaData != null) {
                channel = String.valueOf(applicationInfo.metaData.get("UMENG_CHANNEL"));

            }
        } catch (NameNotFoundException e) {
            throw new RuntimeException(
                    "you must set " + "" + " and " + "" + "  in your manifest file.", e);
        }

        return channel;
    }

    /*
     * 初始化Iamgxeload
     * @param applicationContext
     */
    private void initImageLoader(Context applicationContext) {
        //File cacheDir = StorageUtils.getOwnCacheDirectory(applicationContext, "imageloader/Cache/");
        @SuppressWarnings("deprecation")
//		ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
//				applicationContext).threadPriority(Thread.NORM_PRIORITY - 2)
//				.denyCacheImageMultipleSizesInMemory()
//				.diskCacheFileNameGenerator(new Md5FileNameGenerator())
//				.memoryCacheSize(5 * 1024 * 1024)
//				.diskCacheSize(5 * 1024 * 1024)
//				.discCache( new UnlimitedDiscCache(new File(Environment
//		                .getExternalStorageDirectory()
//		                + "/myApp/imgCache")))//自定义缓存目录
//				// 50 Mb
//				.tasksProcessingOrder(QueueProcessingType.LIFO)
//				//.diskCache(new UnlimitedDiscCache(cacheDir))
////				.memoryCache(new WeakMemoryCache())
////				.memoryCache(new LRULimitedMemoryCache(20*1024*1024)) //回收算法
//				.writeDebugLogs() // Remove for release app
//				.build();
//		ImageLoader.getInstance().init(config);
                DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
                .cacheInMemory().cacheOnDisc().build();

        ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
                getApplicationContext()).defaultDisplayImageOptions(defaultOptions)
                .threadPriority(Thread.NORM_PRIORITY - 2)
                .denyCacheImageMultipleSizesInMemory()
                .discCacheFileNameGenerator(new Md5FileNameGenerator())
                .tasksProcessingOrder(QueueProcessingType.LIFO).build();
        ImageLoader.getInstance().init(config);

    }

    public void onClearMemoryClick(View view) {
//	    Toast.makeText(this, "清除内存缓存成功", Toast.LENGTH_SHORT).show();
        ImageLoader.getInstance().clearMemoryCache();  // 清除内存缓存
    }

    public void onClearDiskClick(View view) {
//	    Toast.makeText(this, "清除本地缓存成功", Toast.LENGTH_SHORT).show();
        ImageLoader.getInstance().clearDiskCache();  // 清除本地缓存
    }

    public void display(String imgurl, ImageView imageView, int defaultPicId, int round) {
        if (imgurl.length() > 5) {
            String str;
            if (imgurl.subSequence(0, 5).equals("https")) {
                str = imgurl.substring(0, 4) + imgurl.substring(5, imgurl.length());
            } else {
                str = imgurl;
            }
            imageLoader.displayImage(str, imageView, displayImageOptions(defaultPicId, round));
        } else {
            imageLoader.displayImage(imgurl, imageView, displayImageOptions(defaultPicId, round));
        }
    }

    public void displayid(ImageView imageView, int defaultPicId) {

        imageLoader.displayImage("drawable://" + defaultPicId, imageView);

    }

    public void download(String url) {
        //获得图片的地址


        //Target
        Target target = new Target() {

            @Override
            public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
                String imageName = "usericon" + ".png";

                File dcimFile = FileUtils
                        .getDCIMFile(FileUtils.PATH_PHOTOGRAPH, imageName);

//                LogCat.i("bitmap="+bitmap);
                FileOutputStream ostream = null;
                try {
                    ostream = new FileOutputStream(dcimFile);
                    bitmap.compress(Bitmap.CompressFormat.PNG, 100, ostream);
                    ostream.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
                Editor editor = sha.edit();
                editor.putString("fileicon", dcimFile + "");
                editor.commit();

//                Toast.makeText(getApplicationContext(),"图片下载至:"+dcimFile,Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onBitmapFailed(Drawable errorDrawable) {

            }

            @Override
            public void onPrepareLoad(Drawable placeHolderDrawable) {

            }
        };
        Log.e("imageurl", url);
        //Picasso下载
        Picasso.with(getApplicationContext()).load(url).into(target);

    }

    //如果这里不传第三个参数，那么图片容易错位
    public void display(String imgurl, ImageView imageView) {
        if (imgurl.length() > 5) {
            String str;
            if (imgurl.subSequence(0, 5).equals("https")) {
                str = imgurl.substring(0, 4) + imgurl.substring(5, imgurl.length());
            } else {
                str = imgurl;
            }
            imageLoader.displayImage(str, imageView, displayImageOptions(R.drawable.logo));
//            imageLoader.displayImage(str, imageView);
        } else {
            imageLoader.displayImage(imgurl, imageView, displayImageOptions(R.drawable.logo));
//            imageLoader.displayImage(imgurl, imageView);

        }
    }

    public void display2(String imgurl, ImageView imageView) {
        if (imgurl.length() > 5) {
            String str;
            if (imgurl.subSequence(0, 5).equals("https")) {
                str = imgurl.substring(0, 4) + imgurl.substring(5, imgurl.length());
            } else {
                str = imgurl;
            }
//            imageLoader.displayImage(str, imageView, displayImageOptions(R.drawable.logo));
            imageLoader.displayImage(str, imageView);
        } else {
//            imageLoader.displayImage(imgurl, imageView, displayImageOptions(R.drawable.logo));
            imageLoader.displayImage(imgurl, imageView);
        }
    }

    public DisplayImageOptions displayImageOptions(int resId) {
        // 当options对象不为空并且defaultid与resid 且返回options对象
        //if (null != options) {
        //	return options;
        //}
        options = null;
        options = new DisplayImageOptions.Builder()
                .showImageOnLoading(resId)
                .showImageForEmptyUri(resId)
                .showImageOnFail(resId)
                .cacheInMemory(false)//设置下载的图片是否缓存在内存中
                .cacheOnDisk(true)//设置下载的图片是否缓存在SD卡中
                .considerExifParams(true)
                .imageScaleType(ImageScaleType.EXACTLY)
                .bitmapConfig(Bitmap.Config.RGB_565)
                .displayer(new RoundedBitmapDisplayer(1)).build();//圆角
        return options;
    }

    public DisplayImageOptions displayImageOptions(int resId, int round) {
        // 当options对象不为空并且defaultid与resid 且返回options对象
        //if (null != options) {
        //	return options;
        //}
        options = null;
        options = new DisplayImageOptions.Builder()
                .showImageOnLoading(resId)
                .showImageForEmptyUri(resId)
                .showImageOnFail(resId)
                .cacheInMemory(false)//设置下载的图片是否缓存在内存中
                .cacheOnDisk(true)//设置下载的图片是否缓存在SD卡中
                .considerExifParams(true)
                .imageScaleType(ImageScaleType.EXACTLY)
                .bitmapConfig(Bitmap.Config.RGB_565)
                .displayer(new RoundedBitmapDisplayer(round)).build();//圆角
        return options;
    }


    public void addActvity(Activity activity) {
        records.add(activity);
    }

    public void removeActvity(Activity activity) {
        records.remove(activity);
    }

    public void exit() {
        for (Activity activity : records) {
            activity.finish();
        }
    }
}
